/**
 * 
 */
package com.magnusart.scrumppm.presenters;

import static com.magnusart.scrumppm.model.States.Transition.NEW_TO_DETAILS;

import java.util.Observable;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;

import com.magnusart.scrumify.dao.CommonDAO;
import com.magnusart.scrumppm.gui.ProjectCreateNew;
import com.magnusart.scrumppm.model.Project;
import com.magnusart.scrumppm.model.ProjectBuilder;
import com.magnusart.scrumppm.model.States.Transition;
/**
 * This class handles retrieving data input from the user, 
 * validate it and add it to the database.
 * @author Magnus Andersson
 *
 */
public class CreateNewPresenter extends AbstractPresenter<ProjectCreateNew, CommonDAO<Project, Project, ProjectBuilder>>
{
	/**
	 * 
	 */
	public CreateNewPresenter( ProjectCreateNew view, CommonDAO<Project, Project, ProjectBuilder> dao ) {
		super( view, dao );
		
		addListeners();
		initView();
	}

	@Override
	protected void addListeners() {
		view.getCreateProjectButton().addListener( SWT.Selection, this );
	}

	@Override
	protected void initView() {
		// Nothing to do
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
	 */
	/*
	 * Do not forget to add an event listener for each case!
	 */
	@Override
	public void handleEvent( Event e ) {
		if( e.widget.getData() instanceof WidgetTypes ) {
			WidgetTypes s = (WidgetTypes)( e.widget.getData() );
			switch( s ) {
				case CreateNewButton:
					doCreateNewProject();
					break;
			}
		}
	}

	private void doCreateNewProject() {
		String projectName = view.getProjectNameText().getText();
		String projectDesc = view.getProjectDetailsTextArea().getText();
		
		ProjectBuilder builder = new ProjectBuilder();
		builder.setName( projectName );
		builder.setDescription( projectDesc );
		
		Project project = dao.add( new Project( builder ), new Project( builder ) );
		
		if( project instanceof Project ) {
			GlobalEvents.setCurrentProject( project );
			GlobalEvents.refreshProjectListings();
			Transition.to( NEW_TO_DETAILS );
		}
	}

	/* (non-Javadoc)
	 * @see com.magnusart.scrumppm.presenters.AbstractPresenter#update(java.util.Observable, java.lang.Object)
	 */
	@Override
	public void update( Observable obs, Object obj ) {
		// TODO Auto-generated method stub
		
	}
}
